package cn.edu.controller;

import cn.edu.entity.JournalEntity;
import cn.edu.entity.UserEntity;
import cn.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping(value = "user")
@SessionAttributes({"user", "journals"})
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(HttpSession httpSession, SessionStatus sessionStatus, ModelMap modelMap) {
        UserEntity userEntity = (UserEntity) httpSession.getAttribute("user");
        if (userEntity != null) {
            userEntity = userService.get(userEntity.getId());
            modelMap.addAttribute("user",userEntity);
            modelMap.addAttribute("journals",userEntity.getJournalEntities());
            sessionStatus.setComplete();
            return "logined";
        }
        return "login";
    }

    @RequestMapping(value = "logout",method = RequestMethod.GET)
    public String lougout(HttpSession httpSession,SessionStatus sessionStatus){
        httpSession.removeAttribute("user");
        httpSession.removeAttribute("journals");
        sessionStatus.setComplete();
        return "redirect: /woodmgr/user/login";
    }

    @RequestMapping(value = "showDatas",method = RequestMethod.GET)
    @ResponseBody
    public List<JournalEntity> showDatas(HttpSession httpSession){
        UserEntity userEntity = (UserEntity) httpSession.getAttribute("user");
        userEntity = userService.get(userEntity.getId());
        return userEntity.getJournalEntities();
    }

    @RequestMapping(value = "check", method = RequestMethod.POST)
    public String check(String username, String password, HttpSession httpSession) {

        UserEntity userEntity = userService.check(username, password);
        httpSession.setAttribute("user",userEntity);
        httpSession.setAttribute("journals",userEntity.getJournalEntities());
        return "redirect: /woodmgr/user/login";
    }


}